package com.hmz.backend.api;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回格式
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
    @SneakyThrows //这个是自动检查异常
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果返回的是个字符串的话,如果Controller直接返回String的话，SpringBoot是直接返回，故我们需要手动转换成json。
        if(o instanceof String)  return objectMapper.writer().writeValueAsString(ResultData.success(o));
        //如果出现了异常则会被全局异常处理器捕获，此时已经封装成了ResultData格式则不用进行再次封装
        if(o instanceof JSONObject) return ResultData.success(o); //后期再改
        if(o instanceof ResultData) return o; //直接返回即可
        return ResultData.success(o);
    }

}
